package com.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.math.NumberUtils;

import com.log.LogUtil;

public class DateUtil {
	public static SimpleDateFormat dfYMD = new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat dfYMDH = new SimpleDateFormat("yyyy-MM-dd HH");
	public static SimpleDateFormat dfYMDHM = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	public static SimpleDateFormat dfYMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat dfYYYYMM = new SimpleDateFormat("yyyyMM");
	public static Date getDateByObj(Object val) {
		Date d = null;
		if (val == null || val.toString().trim().equals("")) return null;
		String value = val.toString().trim();
		String type = val.getClass().getSimpleName();
		try {
			if (type.equalsIgnoreCase("date")
					|| type.equalsIgnoreCase("timestamp")
					|| type.equalsIgnoreCase("datetime")) {
				d = (Date) val;
			} else if (type.equalsIgnoreCase("String")) {
				int len = value.length();
				if (len < 8 || !NumberUtils.isNumber(value.substring(0, 4))) {
					throw new RuntimeException("");
				} else if (len <= 10) {
					d = dfYMD.parse(value);
				} else if (len <= 13) {
					d = dfYMDH.parse(value);
				} else if (len <= 16) {
					d = dfYMDHM.parse(value);
				} else if (len <= 19) {
					d = dfYMDHMS.parse(value);
				} else {
					d = dfYMDHMS.parse(value);
				}
			} else if (type.equalsIgnoreCase("long")
					|| type.equalsIgnoreCase("integer")) {
				d = new Date(Long.parseLong(value));
			} else {
				throw new ParseException("Unparseable date: " + value, 0);
			}
		} catch (Exception e) {
			LogUtil.warn(e);
		}
		return d;
	}

	public static String getDateStr(Date date) {
		if (date == null)
			return "";
		else {
			return dfYMDHMS.format(date);
		}
	}

	public static String getDateStr(Object date) {
		if (date == null || date.toString().trim().equals(""))
			return "";
		else {
			return dfYMDHMS.format(getDateByObj(date));
		}
	}
}
